const fs = require('fs');
const path = require('path');

module.exports =  function viteAndroidBuildPlugin(options) {
  return {
    name: "vite-android-build-plugin",
    async closeBundle() {
      const out = options && options.outDir ? options.outDir : "dist";
      const outDir = path.resolve(process.cwd(), out);
      const htmlFilePath = path.join(outDir, "index.html");
      if (fs.existsSync(htmlFilePath)) {
        let htmlContent = fs.readFileSync(htmlFilePath, "utf-8");

        const htmlArr = htmlContent.match(/.*\n/g) || [];
        let result = "";
        htmlArr.forEach((v) => {
          v = v
            .replace(/script ?nomodule\s?/g, "script ")
            .replace(/\s?crossorigin\s?/g, " ")
            .replace(/<link rel="modulepreload" href="[^"]+\.js">/g, "")
            .replace(
              "System.import(document.getElementById('vite-legacy-entry').getAttribute('src'))",
              ""
            )
            .replace(/data-src/g, "src");
          if (!v.includes(`script type="module"`)) {
            result += v;
          }
        });
        fs.writeFileSync(htmlFilePath, result, "utf-8");
        console.log("构建处理完成!");

        if (options && options.copyToAndroidPath) {
          fs.rm(options.copyToAndroidPath, { recursive: true }, (err) => {
            fs.cp(
              outDir,
              options.copyToAndroidPath,
              { recursive: true },
              (err) => {
                if (err) {
                  console.error(err);
                  return;
                }
                console.info("复制成功！");
              }
            );
          });
        }
      }
    },
  };
}
